(library (handlers)
  (export index
          not-found-404
          debug
          hello-world
          minimal-static-asset)
  (import
   (except (rnrs base) let-values)
   (only (guile) lambda* λ error when display sleep)

   ;; Guile modules
   ;; alist->hash-table
   (prefix (ice-9 hash-table) ice9-hash-table:)
   ;; Guile exception handling
   (ice-9 exceptions)
   (ice-9 session)
   ;; for bytevector operations
   (ice-9 binary-ports)

   ;; SRFIs
   ;; hash tables
   (prefix (srfi srfi-69) srfi-69:)
   ;; receive form
   (prefix (srfi srfi-8) srfi-8:)
   ;; let-values
   (prefix (srfi srfi-11) srfi-11:)
   ;; list utils
   (prefix (srfi srfi-1) srfi-1:)

   ;; web server, concurrent
   (fibers web server)
   ;; standard web library
   (web request)
   (web response)
   (web uri)
   (sxml simple)
   ;; custom modules
   (path-handling)
   (web-path-handling)
   (file-reader)
   (mime-types)
   (prefix (logging) log:)
   (prefix (templates) template:)
   (prefix (templates vocabulary) tmpl-voc:)
   (prefix (templates debug) tmpl-dbg:)
   (prefix (response-utils) resp:)))


(define vocabulary
  '(("I" "wo3" "我")
    ("You" "ni3" "你")
    ("good" "hao3" "好")))


(define index
  (λ (request body)
    "Show app start screen."
    (log:debug "handler: index")
    (resp:respond
     (tmpl-voc:vocabulary-overview request
                                   body
                                   vocabulary)
     #:status 200
     #:title "Overview")))


;; Next we define some handlers, which take care of handling
;; specific routes.

(define not-found-404
  (λ (request body)
    "Answer with a 404 HTTP status code."
    (values (build-response #:code 404)
            (string-append "requested resource not found: "
                           (uri->string (request-uri request))))))


(define debug
  (lambda (request body)
    "The debug-handler will put all request headers into the
rendered HTML, so that we can see them on the page."
    (log:debug "responding using debug handler")
    (resp:respond
     ;; Inside respond the SXML will be put into a template,
     ;; so there is no need to add html or body tags.
     (tmpl-dbg:debug-table request body))))


(define minimal-static-asset
  (λ (request body)
    (log:debug "responding using minimal-static-asset-handler")
    (let ([status 200]
          [content-type-params '((charset . "utf-8"))]
          [content-type 'text/css]
          [extra-headers '()])
      (values (build-response #:code status
                              ;; headers are an alist
                              #:headers
                              `((content-type . (,content-type ,@content-type-params))
                                ,@extra-headers))
              "body {margin: none}"))))
